package com.wframe.project.former.web.marketing;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.frame.database.JdataBean;
import com.frame.database.PageResult;
import com.frame.pageform.DataPageForm;
import com.wframe.project.former.dataservices.marketing.FullGiftsPromotionsService;
import com.wframe.project.former.dataservices.marketing.FullGiftsService;
import com.wframe.project.former.dataservices.marketing.PromotionsService;
import com.wframe.project.former.dataservices.products.ProductClassService;
import com.wframe.project.former.dataservices.products.ProductService;
import com.wframe.project.jnd.entity.Promotion;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.wframe.project.former.dataservices.marketing.SingService;

import java.util.*;

/**
 * Created by Administrator on 2017/6/14.
 */
public class FullGiftsPromotionPage extends DataPageForm {
    private static FullGiftsService fullGiftsService = FullGiftsService.getIntance();
    private static SingService singService = SingService.getIntance();
    private static FullGiftsPromotionsService fullGiftsPromotionsService = FullGiftsPromotionsService.getIntance();
    private PromotionsService promotionsService = PromotionsService.getIntance();
    private ProductClassService pcservice = ProductClassService.getIntance();
    private ProductService service = ProductService.getIntance();
    private JdataBean bean;
    private int rows = 1;

    @Override
    public String execute() throws Exception {
        setPagination(fullGiftsService.queryFullGiftsList(bean, getPageSize_(), getPageNum()));
        return "/webadmin/marketing/fullgiftsList.jsp";
    }

    @Override
    public String show() throws Exception {
        bean = fullGiftsPromotionsService.findOne(bean.getString("id"));
        if ("2".equals(bean.getString("product_type")) || "1".equals(bean.getString("product_type"))) {
            if ("2".equals(bean.getString("product_type"))) {
                List<JdataBean> productClassList = promotionsService.getSingleProductList(bean.getString("product_val"));
                if(productClassList.size() != 0) {
                    for (JdataBean jdataBean : productClassList) {
                        jdataBean.put("price",promotionsService.getProducrPrice(String.valueOf(jdataBean.get("id"))));
                        jdataBean.put("moneyOffType", promotionsService.getProductMoneyOffTypeById(String.valueOf(jdataBean.get("id"))));
                        jdataBean.put("classname", pcservice.getProductClassName(String.valueOf(jdataBean.getString("id"))));
                        List<JdataBean> jdataBeans_attribute = service.queryAllModelAttrAndVal("1", String.valueOf(jdataBean.get("id")), 1);
                        for (JdataBean attr : jdataBeans_attribute) {
                            jdataBean.put(attr.getString("code"), attr.get("val"));
                        }
                    }
                    getRequest().setAttribute("productitems_to", productClassList);
                }
            }
            if ("1".equals(bean.getString("product_type"))) {
                JdataBean singleProducData = promotionsService.getSingleProduct(bean.getString("product_val"));
                if(singleProducData != null) {
                    singleProducData.put("price",promotionsService.getProducrPrice(String.valueOf(singleProducData.get("id"))));
                    singleProducData.put("moneyOffType", promotionsService.getProductMoneyOffTypeById(String.valueOf(singleProducData.get("id"))));
                    singleProducData.put("classname", pcservice.getProductClassName(String.valueOf(singleProducData.getString("id"))));
                    List<JdataBean> jdataBeans_attribute = service.queryAllModelAttrAndVal("1", String.valueOf(singleProducData.get("id")), 1);
                    for (JdataBean attr : jdataBeans_attribute) {
                        singleProducData.put(attr.getString("code"), attr.get("val"));
                    }
                    getRequest().setAttribute("singleProducitem", singleProducData);
                }
            }

        }
        if ("3".equals(bean.getString("product_type"))) {
            String moneyOff_classid = bean.getString("product_val");
            getRequest().setAttribute("moneyOff_classid", moneyOff_classid);
        }
        getRequest().setAttribute("controlsales", promotionsService.promotionControlsale(bean.getInt("id")));
        return "/webadmin/marketing/fullgiftsListEdit.jsp";
    }

    @Override
    public String toDel() throws Exception {
        return null;
    }

    @Override
    public boolean toUpdate() throws Exception {
        try {
            if(StringUtils.isNotBlank(bean.getString("promotid"))) {
                Map key = new HashMap();
                key.put("id",bean.getString("promotid"));
                JdataBean updateData = new JdataBean();
                updateData.put("promotion_type",null);
                promotionsService.update(updateData.getDataMap(),key);
            }
            JdataBean basedata = new JdataBean();
            basedata.put("promotion_type", Promotion.Type.PURCHASE_GIFT.ordinal());
            basedata.put("platform", bean.getString("platform"));
            basedata.put("start_time", bean.getString("start_time"));
            basedata.put("end_time", bean.getString("end_time"));
            basedata.put("description", bean.getString("description"));
            basedata.put("name", bean.getString("name"));
            basedata.put("sort_value", bean.getString("sort_value"));
            basedata.put("weight", Promotion.Weight.MONEY_OFF.ordinal());
            basedata.put("second_priority", Promotion.Priority.FIRST.ordinal());
            basedata.put("district_description",bean.getString("district_description"));
            basedata.put("time", bean.getString("time"));
            basedata.put("items", bean.getString("gift"));
            int productType = bean.getInt("product_type");
            switch (productType) {
                case 0:
                    basedata.put("product_type", Promotion.PruductType.ALL.ordinal());
                    basedata.put("product_val", null);
                    break;
                case 2:
                    String products = bean.getString("product_val");
                    if (products.length() > 2) {
                        JSONArray arr = JSONArray.parseArray(products);
                        if (arr.size() > 0) {
                            if (arr.size() == 1) {
                                basedata.put("product_type", Promotion.PruductType.SINGLE.ordinal());
                                basedata.put("product_val", arr.get(0));
                            } else {
                                basedata.put("product_type", Promotion.PruductType.SOME.ordinal());
                                basedata.put("product_val", bean.getString("product_val"));
                            }
                        }
                    } else {
                        basedata.put("product_type",null);
                        basedata.put("product_val", null);
                    }
                    break;
                case 3:
                    basedata.put("product_type", Promotion.PruductType.CATEGORY.ordinal());
                    if (StringUtils.isNotBlank(bean.getString("classid")) && !"null".equals(bean.getString("classid"))) {
                        basedata.put("product_val", bean.getString("classid"));
                    } else {
                        basedata.put("product_type",null);
                        basedata.put("product_val",null);
                    }
                    break;
            }

            List<JdataBean> beanList = null;
            //查询商品是否已经参加活动
            if (0 == productType) {
                beanList = fullGiftsPromotionsService.canCreate();
                if (beanList.size() != 0) {
                    if (StringUtils.isNotBlank(bean.getString("promotid"))) {
                        Map key = new HashMap();
                        key.put("id",bean.getString("promotid"));
                        JdataBean updateData = new JdataBean();
                        updateData.put("promotion_type",3);
                        promotionsService.update(updateData.getDataMap(), key);
                    }
                    getJsonObject().put("state", "no");
                    return false;
                }
            }

            //查询商品是否已经参加活动
            if (2 == productType) {
                if(StringUtils.isNotBlank(bean.getString("product_val")) ) {
                    List<String> ids = JSON.parseArray(bean.getString("product_val"), String.class);
                    if (ids.size() != 0) {
                        beanList = fullGiftsPromotionsService.canCreate(ids);
                        if (beanList.size() != 0) {
                            if (StringUtils.isNotBlank(bean.getString("promotid"))) {
                                Map key = new HashMap();
                                key.put("id",bean.getString("promotid"));
                                JdataBean updateData = new JdataBean();
                                updateData.put("promotion_type",3);
                                promotionsService.update(updateData.getDataMap(), key);
                            }
                            getJsonObject().put("state", "no");
                            return false;
                        }
                    }
                }
            }
            //查询类目是否参加了活动
            if (3 == productType) {
                if (StringUtils.isNotBlank(bean.getString("classid")) && !bean.getString("classid").equals("null")) {
                    beanList = fullGiftsPromotionsService.canCreate(bean.getInt("classid"));
                    if (beanList.size() != 0) {
                        if (StringUtils.isNotBlank(bean.getString("promotid"))) {
                            Map key = new HashMap();
                            key.put("id",bean.getString("promotid"));
                            JdataBean updateData = new JdataBean();
                            updateData.put("promotion_type",3);
                            promotionsService.update(updateData.getDataMap(), key);
                        }
                        getJsonObject().put("state", "no");
                        return false;
                    }

                }
            }
            Map key = new HashMap();
            String promotid = bean.getString("promotid");
            if (StringUtils.isBlank(promotid)) {
                basedata.put("state", 1);
                basedata.put("create_time", new Date());
                promotid = fullGiftsPromotionsService.saveFullGifts(basedata);
            } else {
                key.put("id", promotid);
                fullGiftsPromotionsService.updatFullGifts(basedata, key);
            }
            //保存控销数据
            if (StringUtils.isNotBlank(promotid)) {
                org.json.JSONArray controlsales = null;
                if (StringUtils.isNotBlank(bean.getString("controlsales")))
                    controlsales = new org.json.JSONArray(bean.getString("controlsales"));
                singService.addControlsalesSingLe(promotid, controlsales, bean.getString("controlusers"));
            }
            getJsonObject().put("state", "ok");
        } catch (Exception e) {
            Logger.getLogger(this.getClass()).error("保存满赠活动信息错误：", e);
            getJsonObject().put("state", e.getMessage());
        }
        return false;
    }

    public String fullGiftsAdd() throws Exception {
        return "/webadmin/marketing/fullgiftsAdd.jsp";
    }

    public String FullGiftsUpDataStop() throws Exception {
        fullGiftsPromotionsService.FullGiftsUpDataStop(bean.getInt("promotionid"), bean.getInt("state"));
        return getJsonObject().toString();
    }


    //选择商品
    public String chooseMoneyList() throws Exception {
        PageResult pr = fullGiftsPromotionsService.queryMoneyProduct(bean, 10, getPageNum());
        List<JdataBean> list = pr.getList();
        String[] productids = new String[list.size()];
        for(int i = 0 ; i < list.size() ; i++) {
            productids[i] = list.get(i).getString("id");
        }
        List<JdataBean> PromotionTypes = promotionsService.getProductPromotionTypeByIds(productids);
        for (JdataBean product : list) {
            //product.put("price",promotionsService.getProducrPrice(String.valueOf(product.get("id"))));
            //product.put("moneyOffType",promotionsService.getProductMoneyOffTypeById(String.valueOf(product.get("id"))));
            for(JdataBean types : PromotionTypes) {
                if(product.getString("id") != null && product.getString("id").equals(types.getString("id"))) {
                    product.put("moneyOffType",types.getString("pms"));
                    product.put("price",types.getString("price"));
                }
            }
            if (product.getString("moneyOffType") != null) {
                if(product.getString("moneyOffType").contains("满赠促销")) {
                    product.put("product_type_money_off","已参加满赠活动");
                }else if( product.getString("moneyOffType").contains("满减促销")) {
                    product.put("product_type_money_off","已参加满减活动");
                }
            }

            List<JdataBean> jdataBeans = service.queryAllModelAttrAndVal("1", String.valueOf(product.get("id")), 1);
            for (JdataBean attr : jdataBeans) {
                product.put(attr.getString("code"), attr.get("val"));
            }

            product.put("classname", pcservice.getProductClassName(String.valueOf(product.getString("id"))));

        }

        setPagination(pr);
        return "/webadmin/marketing/moneyOffProductList.jsp";
    }



    public String chooseGifts() throws Exception {
        String giftName = "";
        if (bean != null) {
            if (StringUtils.isNotBlank(bean.getString("giftName"))) {
                giftName = bean.getString("giftName");
            }
        }
        int start = (rows-1)*10;
        List<JdataBean> list = fullGiftsPromotionsService.chooseGifts(giftName,start);
        ArrayList<Map<String,String>> gifts = new ArrayList<Map<String,String>>();
        for(JdataBean data : list) {
            gifts.add(data.getDataMap());
        }

        getJsonObject().put("gifts", gifts);
        return getJsonObject().toString();
    }

    public JdataBean getBean() {
        return bean;
    }

    public void setBean(JdataBean bean) {
        this.bean = bean;
    }

    public void setRows(int rows){
        this.rows = rows;
    }
    public int getRows() {
        return rows;
    }
}
